from django.http import JsonResponse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.contrib.auth import authenticate
from django.db import OperationalError, DatabaseError
import json
import requests

from utils.JWTTool import jwtTool


@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def login(request):
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)

    try:
        try:
            body_unicode = request.body.decode("utf-8") or "{}"
            payload = json.loads(body_unicode)
        except json.JSONDecodeError:
            return JsonResponse({"code": 400, "msg": "请求体不是合法 JSON", "data": None}, status=400)

        username = (payload.get("username") or "").strip()
        password = payload.get("password") or ""
        if not username or not password:
            return JsonResponse({"code": 400, "msg": "用户名或密码不能为空", "data": None}, status=400)
        try:
            user = authenticate(request, username=username, password=password)
        except (OperationalError, DatabaseError):
            return JsonResponse({
                "code": 500,
                "msg": "数据库未初始化或迁移未执行。请运行: python manage.py migrate，并创建用户后再试。",
                "data": None
            }, status=500)

        if user is None:
            return JsonResponse({"code": 401, "msg": "用户名或密码错误", "data": None}, status=401)

        # 更新最后登录时间
        from django.utils import timezone
        user.last_login = timezone.now()
        user.save(update_fields=['last_login'])

        token = jwtTool.generate_token(user.id)
        
        # 返回用户基本信息
        user_data = {
            "id": user.id,
            "username": user.username,
            "email": user.email or "",
            "phone": user.phone or "",
            "is_active": user.is_active,
            "date_joined": user.date_joined.isoformat() if user.date_joined else None,
            "last_login": user.last_login.isoformat() if user.last_login else None,
            "loginType": "password"
        }
        
        # 如果有用户详细信息，也包含进来
        try:
            profile = user.profile
            user_data.update({
                "nickname": profile.nickname or "",
                "avatar": profile.avatar or "",
                "gender": profile.gender or "",
                "bio": profile.bio or ""
            })
        except:
            pass  # 用户可能没有profile记录
            
        return JsonResponse({
            "code": 0, 
            "msg": "登录成功", 
            "data": {
                "token": token,
                "user": user_data
            }
        }, status=200)
    except Exception as e:
        return JsonResponse({"code": 500, "msg": str(e), "data": None}, status=500)


@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def dingtalk_login(request):
    """钉钉登录接口 - 返回钉钉OAuth授权URL"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)

    try:
        from urllib.parse import quote
        from django.conf import settings
        
        # 从settings获取钉钉配置
        dingtalk_config = getattr(settings, 'DINGTALK_CONFIG', {})
        client_id = dingtalk_config.get('CLIENT_ID')
        redirect_uri = dingtalk_config.get('REDIRECT_URI', 'http://localhost:5173/auth/dingtalk/callback')
        
        if not client_id:
            return JsonResponse({
                "code": 500, 
                "msg": "钉钉OAuth未配置，请在settings.py中配置DINGTALK_CONFIG", 
                "data": None
            }, status=500)
        
        params = [
            f"redirect_uri={quote(redirect_uri)}",
            "response_type=code",
            f"client_id={client_id}",
            "scope=openid",
            "prompt=consent"
        ]
        url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
        return JsonResponse({"url": url}, status=200)
    except Exception as e:
        return JsonResponse({"code": 500, "msg": str(e), "data": None}, status=500)


@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def dingtalk_callback(request):
    """钉钉OAuth回调处理 - 使用授权码换取用户信息并登录"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        from django.conf import settings
        import requests
        import json
        import traceback

        
        # 获取配置
        dingtalk_config = getattr(settings, 'DINGTALK_CONFIG', {})
        client_id = dingtalk_config.get('CLIENT_ID')
        client_secret = dingtalk_config.get('CLIENT_SECRET')
        
        if not client_id or not client_secret or client_secret == 'YOUR_COMPLETE_SECRET_HERE':
            return JsonResponse({
                "code": 500, 
                "msg": "钉钉OAuth配置不完整。请检查 .env 文件中的 DINGTALK_CLIENT_SECRET 是否为完整的密钥", 
                "data": None
            }, status=500)
        
        # 解析请求数据
        try:
            body_unicode = request.body.decode("utf-8") or "{}"
            payload = json.loads(body_unicode)
        except json.JSONDecodeError:
            return JsonResponse({"code": 400, "msg": "请求体不是合法 JSON", "data": None}, status=400)
        
        auth_code = payload.get("code")
        if not auth_code:
            return JsonResponse({"code": 400, "msg": "缺少授权码", "data": None}, status=400)
        
        # 1. 使用授权码换取access_token
        token_url = "https://api.dingtalk.com/v1.0/oauth2/userAccessToken"
        token_data = {
            "clientId": client_id,
            "clientSecret": client_secret,
            "code": auth_code,
            "grantType": "authorization_code"
        }
        
        token_response = requests.post(token_url, json=token_data)
        
        if token_response.status_code != 200:
            return JsonResponse({
                "code": 500, 
                "msg": f"获取access_token失败: {token_response.text}", 
                "data": None
            }, status=500)
        
        token_result = token_response.json()
        access_token = token_result.get("accessToken")
        if not access_token:
            return JsonResponse({
                "code": 500, 
                "msg": f"获取access_token失败，响应: {token_result}", 
                "data": None
            }, status=500)
        
        # 2. 使用access_token获取用户信息
        user_url = "https://api.dingtalk.com/v1.0/contact/users/me"
        headers = {"x-acs-dingtalk-access-token": access_token}
        
        user_response = requests.get(user_url, headers=headers)
        
        if user_response.status_code != 200:
            return JsonResponse({
                "code": 500, 
                "msg": f"获取用户信息失败: {user_response.text}", 
                "data": None
            }, status=500)
        
        user_info = user_response.json()
        
        # 3. 处理用户信息并创建/更新用户
        dingtalk_id = user_info.get("unionId") or user_info.get("openId")
        username = user_info.get("nick") or f"dingtalk_{dingtalk_id}"
        
        if not dingtalk_id:
            return JsonResponse({
                "code": 500, 
                "msg": f"无法获取钉钉用户ID，用户信息: {user_info}", 
                "data": None
            }, status=500)
        
        # 导入模型
        from .models import User, ThirdPartyLogin, UserProfile
        from django.db import transaction
        
        try:
            with transaction.atomic():
                # 查找是否已存在钉钉登录记录
                third_party_login = None
                user = None

                # 先检查是否有对应的第三方登录记录
                try:
                    third_party_login = ThirdPartyLogin.objects.get(
                        platform='dingtalk',
                        platform_user_id=dingtalk_id
                    )
                    # 更新已存在的记录
                    third_party_login.access_token = access_token
                    third_party_login.platform_user_info = user_info
                    third_party_login.save()
                    user = third_party_login.user
                except ThirdPartyLogin.DoesNotExist:
                    # 检查钉钉返回的邮箱是否已存在
                    user_email = user_info.get("email")
                    if user_email:
                        try:
                            # 如果邮箱存在，直接关联该用户
                            user = User.objects.get(email=user_email)
                        except User.DoesNotExist:
                            user = None

                    # 如果用户不存在，创建新用户
                    if not user:
                        # 生成唯一的用户名
                        base_username = username[:20]  # 限制长度
                        final_username = base_username
                        counter = 1
                        while User.objects.filter(username=final_username).exists():
                            final_username = f"{base_username}_{counter}"
                            counter += 1

                        # 生成唯一的邮箱（使用钉钉ID确保唯一性）
                        if not user_email:
                            user_email = f"{dingtalk_id}@dingtalk.com"

                        # 创建用户
                        user = User.objects.create_user(
                            username=final_username,
                            email=user_email,  # 确保邮箱字段有唯一值
                            password=None,  # 第三方登录不需要密码
                            is_active=True
                        )

                        # 创建用户详细信息
                        UserProfile.objects.create(
                            user=user,
                            nickname=user_info.get("nick", ""),
                            avatar=user_info.get("avatar", "")
                        )

                    # 创建第三方登录记录（无论是新用户还是已有用户）
                    third_party_login = ThirdPartyLogin.objects.create(
                        platform='dingtalk',
                        platform_user_id=dingtalk_id,
                        user=user,
                        access_token=access_token,
                        platform_user_info=user_info
                    )
                
                # 生成JWT token
                token = jwtTool.generate_token(user.id)
                
                return JsonResponse({
                    "code": 0, 
                    "msg": "钉钉登录成功", 
                    "data": {
                        "token": token,
                        "user": {
                            "id": user.id,
                            "username": user.username,
                            "nickname": user.profile.nickname if hasattr(user, 'profile') else "",
                            "avatar": user.profile.avatar if hasattr(user, 'profile') else "",
                            "loginType": "dingtalk"
                        }
                    }
                }, status=200)
                
        except Exception as db_error:
            # 输出详细的异常信息和堆栈
            error_details = f"数据库操作失败: {str(db_error)}\n堆栈信息: {traceback.format_exc()}"
            print(error_details)  # 打印到控制台便于调试
            return JsonResponse({
                "code": 500,
                "msg": error_details,
                "data": None
            }, status=500)
        
    except Exception as e:
        import traceback
        error_details = f"钉钉登录处理失败: {str(e)}\n堆栈信息: {traceback.format_exc()}"
        print(error_details)
        return JsonResponse({"code": 500, "msg": error_details, "data": None}, status=500)


@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def register(request):
    """用户注册接口"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)

    try:
        # 解析请求数据
        try:
            body_unicode = request.body.decode("utf-8") or "{}"
            payload = json.loads(body_unicode)
        except json.JSONDecodeError:
            return JsonResponse({"code": 400, "msg": "请求体不是合法 JSON", "data": None}, status=400)

        # 获取注册信息
        username = (payload.get("username") or "").strip()
        password = payload.get("password") or ""
        confirm_password = payload.get("confirmPassword") or ""
        email = (payload.get("email") or "").strip()
        phone = (payload.get("phone") or "").strip()
        nickname = (payload.get("nickname") or "").strip()

        # 处理空值
        email = email if email else None  # 保留None但不再额外strip()
        phone = phone if phone else None
        nickname = nickname if nickname else None
        # 处理空值 - 将空字符串转为None
        email = email.strip() if email and email.strip() else None
        phone = phone.strip() if phone and phone.strip() else None  
        nickname = nickname.strip() if nickname and nickname.strip() else None

        # 基本验证
        if not username or not password:
            return JsonResponse({"code": 400, "msg": "用户名和密码不能为空", "data": None}, status=400)

        if password != confirm_password:
            return JsonResponse({"code": 400, "msg": "两次输入的密码不一致", "data": None}, status=400)

        # 用户名长度验证
        if len(username) < 2 or len(username) > 32:
            return JsonResponse({"code": 400, "msg": "用户名长度应为2-32个字符", "data": None}, status=400)

        # 密码长度验证
        if len(password) < 6 or len(password) > 64:
            return JsonResponse({"code": 400, "msg": "密码长度应为6-64个字符", "data": None}, status=400)

        # 邮箱格式验证
        if email:
            import re
            email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
            if not re.match(email_pattern, email):
                return JsonResponse({"code": 400, "msg": "邮箱格式不正确", "data": None}, status=400)

        # 手机号格式验证
        if phone:
            import re
            phone_pattern = r'^1[3-9]\d{9}$'
            if not re.match(phone_pattern, phone):
                return JsonResponse({"code": 400, "msg": "手机号格式不正确", "data": None}, status=400)

        from .models import User, UserProfile
        from django.db import transaction
        import uuid  # 新增：用于生成唯一邮箱

        # 检查用户名是否已存在
        if User.objects.filter(username=username).exists():
            return JsonResponse({"code": 400, "msg": "用户名已存在", "data": None}, status=400)

        # 生成唯一邮箱（当用户未提供时）
        if not email:
            # 生成UUID作为唯一标识，避免空值重复
            unique_id = uuid.uuid4().hex[:10]  # 取UUID前10位
            email = f"user_{unique_id}@example.com"  # 格式如：user_a1b2c3@example.com

        # 检查邮箱是否已被注册（包括自动生成的邮箱）
        if User.objects.filter(email=email).exists():
            # 如果自动生成的邮箱意外重复，重新生成
            if "user_" in email and "@example.com" in email:
                unique_id = uuid.uuid4().hex[:10]
                email = f"user_{unique_id}@example.com"
            else:
                return JsonResponse({"code": 400, "msg": "邮箱已被注册", "data": None}, status=400)
        # 检查邮箱是否已被注册
        if email and User.objects.filter(email=email).exists():
            return JsonResponse({"code": 400, "msg": "邮箱已被注册", "data": None}, status=400)

        # 检查手机号是否已被注册
        if phone and User.objects.filter(phone=phone).exists():
            return JsonResponse({"code": 400, "msg": "手机号已被注册", "data": None}, status=400)

        # 创建用户
        try:
            with transaction.atomic():
                # 直接创建用户并包含email（避免后续单独更新）
                # 先创建基本用户（不包含email，避免create_user的默认行为）
                user = User.objects.create_user(
                    username=username,
                    password=password,
                    email=email,  # 确保始终有值
                    is_active=True
                )
                
                # 显式设置email和phone字段（确保None而不是空字符串）
                if email:
                    user.email = email

                # 设置手机号（如果提供）
                if phone:
                    user.phone = phone
                    
                # 如果有email或phone才保存
                if email or phone:
                    user.save()

                # 创建用户详细信息
                UserProfile.objects.create(
                    user=user,
                    nickname=nickname or username
                )

                # 生成JWT token
                token = jwtTool.generate_token(user.id)

                return JsonResponse({
                    "code": 0,
                    "msg": "注册成功",
                    "data": {
                        "token": token,
                        "user": {
                            "id": user.id,
                            "username": user.username,
                            "nickname": nickname or username,
                            "email": email if not email.startswith("user_") else None,  # 对前端隐藏自动生成的邮箱
                            "phone": phone,
                            "loginType": "register"
                        }
                    }
                }, status=200)

        except Exception as db_error:
            return JsonResponse({
                "code": 500,
                "msg": f"注册失败: {str(db_error)}",
                "data": None
            }, status=500)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return JsonResponse({"code": 500, "msg": f"服务器错误: {str(e)}", "data": None}, status=500)


@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def send_sms_code(request):
    """发送短信验证码"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)

    try:
        # 解析请求数据
        try:
            body_unicode = request.body.decode("utf-8") or "{}"
            payload = json.loads(body_unicode)
        except json.JSONDecodeError:
            return JsonResponse({"code": 400, "msg": "请求体不是合法 JSON", "data": None}, status=400)

        phone = (payload.get("phone") or "").strip()

        # 手机号验证
        if not phone:
            return JsonResponse({"code": 400, "msg": "手机号不能为空", "data": None}, status=400)

        import re
        phone_pattern = r'^1[3-9]\d{9}$'
        if not re.match(phone_pattern, phone):
            return JsonResponse({"code": 400, "msg": "手机号格式不正确", "data": None}, status=400)

        # 生成6位随机验证码
        import random
        sms_code = str(random.randint(100000, 999999))

        # 检查发送频率限制（60秒内只能发送一次）
        from utils.redis_client import redis_client
        
        # 检查是否在冷却时间内
        ttl = redis_client.get_sms_code_ttl(phone)
        if ttl > 240:  # 如果剩余时间大于4分钟（总共5分钟-1分钟冷却）
            remaining_seconds = ttl - 240
            return JsonResponse({
                "code": 400,
                "msg": f"请等待{remaining_seconds}秒后再次发送验证码",
                "data": None
            }, status=400)

        # 发送短信
        try:
            from django.conf import settings
            
            # 检查是否为开发模式
            if getattr(settings, 'DEBUG', False):
                # 开发模式：直接存储验证码到Redis，不实际发送短信
                success = redis_client.set_sms_code(phone, sms_code, 300)  # 5分钟过期
                
                if success:
                    # 在控制台输出验证码信息（JSON格式）
                    from utils.sms_debug_tools import print_sms_code_info
                    print_sms_code_info(phone, sms_code, 300, "development")
                    
                    return JsonResponse({
                        "code": 0,
                        "msg": "验证码发送成功",
                        "data": {
                            "phone": phone,
                            "expire_time": 300
                        }
                    }, status=200)
                else:
                    return JsonResponse({
                        "code": 500,
                        "msg": "验证码存储失败",
                        "data": None
                    }, status=500)
            else:
                # 生产模式：使用容联云发送短信
                from utils.send import send_message
                result = send_message(phone, sms_code)
                
                print(f"短信发送结果: {result}")  # 调试信息
                
                # 容联云成功状态码通常是 "000000"
                if result.get("statusCode") == "000000" or result.get("status") == "success":
                    # 将验证码存储到Redis
                    success = redis_client.set_sms_code(phone, sms_code, 300)  # 5分钟过期
                    
                    if success:
                        return JsonResponse({
                            "code": 0,
                            "msg": "验证码发送成功",
                            "data": {
                                "phone": phone,
                                "expire_time": 300
                            }
                        }, status=200)
                    else:
                        return JsonResponse({
                            "code": 500,
                            "msg": "验证码发送成功但存储失败",
                            "data": None
                        }, status=500)
                else:
                    error_msg = result.get('statusMsg', result.get('msg', '未知错误'))
                    print(f"短信发送失败: {error_msg}")  # 调试信息
                    return JsonResponse({
                        "code": 500,
                        "msg": f"短信发送失败: {error_msg}",
                        "data": None
                    }, status=500)

        except Exception as sms_error:
            print(f"短信发送异常: {str(sms_error)}")  # 调试信息
            import traceback
            traceback.print_exc()
            return JsonResponse({
                "code": 500,
                "msg": f"短信发送异常: {str(sms_error)}",
                "data": None
            }, status=500)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return JsonResponse({"code": 500, "msg": f"服务器错误: {str(e)}", "data": None}, status=500)


@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def sms_login(request):
    """短信验证码登录"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)

    try:
        # 解析请求数据
        try:
            body_unicode = request.body.decode("utf-8") or "{}"
            payload = json.loads(body_unicode)
        except json.JSONDecodeError:
            return JsonResponse({"code": 400, "msg": "请求体不是合法 JSON", "data": None}, status=400)

        phone = (payload.get("phone") or "").strip()
        sms_code = (payload.get("smsCode") or "").strip()

        # 基本验证
        if not phone or not sms_code:
            return JsonResponse({"code": 400, "msg": "手机号和验证码不能为空", "data": None}, status=400)

        # 手机号格式验证
        import re
        phone_pattern = r'^1[3-9]\d{9}$'
        if not re.match(phone_pattern, phone):
            return JsonResponse({"code": 400, "msg": "手机号格式不正确", "data": None}, status=400)

        # 验证码格式验证
        if len(sms_code) != 6 or not sms_code.isdigit():
            return JsonResponse({"code": 400, "msg": "验证码应为6位数字", "data": None}, status=400)

        # 验证短信验证码
        from utils.redis_client import redis_client
        
        # 从Redis获取验证码
        cached_code = redis_client.get_sms_code(phone)

        if not cached_code:
            return JsonResponse({"code": 400, "msg": "验证码已过期或不存在", "data": None}, status=400)

        if cached_code != sms_code:
            return JsonResponse({"code": 400, "msg": "验证码错误", "data": None}, status=400)

        # 删除已使用的验证码
        redis_client.delete_sms_code(phone)

        from .models import User, UserProfile
        from django.db import transaction
        import uuid  # 新增：用于生成唯一邮箱

        try:
            with transaction.atomic():
                # 查找或创建用户
                user = None
                try:
                    user = User.objects.get(phone=phone)
                except User.DoesNotExist:
                    # 用户不存在，创建新用户
                    import random
                    username = f"user_{phone[-4:]}{random.randint(1000, 9999)}"
                    while User.objects.filter(username=username).exists():
                        username = f"user_{phone[-4:]}{random.randint(1000, 9999)}"

                    # 生成唯一邮箱（使用手机号+UUID确保唯一性）
                    unique_id = uuid.uuid4().hex[:8]
                    email = f"sms_{phone}_{unique_id}@example.com"

                    # 确保生成的邮箱绝对唯一
                    while User.objects.filter(email=email).exists():
                        unique_id = uuid.uuid4().hex[:8]
                        email = f"sms_{phone}_{unique_id}@example.com"

                    # 创建用户时直接设置唯一邮箱
                    
                    user = User.objects.create_user(
                        username=username,
                        email=email,  # 设置唯一邮箱
                        is_active=True
                    )
                    user.phone = phone
                    user.save()

                    # 创建用户详细信息
                    UserProfile.objects.create(
                        user=user,
                        nickname=f"用户{phone[-4:]}"
                    )

                # 更新最后登录时间
                from django.utils import timezone
                user.last_login = timezone.now()
                user.save(update_fields=['last_login'])

                # 生成JWT token
                token = jwtTool.generate_token(user.id)

                return JsonResponse({
                    "code": 0,
                    "msg": "短信登录成功",
                    "data": {
                        "token": token,
                        "user": {
                            "id": user.id,
                            "username": user.username,
                            "nickname": user.profile.nickname if hasattr(user, 'profile') else "",
                            "phone": user.phone,
                            "loginType": "sms",
                            # 对前端隐藏自动生成的邮箱
                            "email": None
                            
                        }
                    }
                }, status=200)

        except Exception as db_error:
            return JsonResponse({
                "code": 500,
                "msg": f"数据库操作失败: {str(db_error)}",
                "data": None
            }, status=500)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return JsonResponse({"code": 500, "msg": f"服务器错误: {str(e)}", "data": None}, status=500)


@csrf_exempt
@require_http_methods(["POST", "OPTIONS"])
def check_sms_status(request):
    """查询短信验证码状态"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)

    try:
        # 解析请求数据
        try:
            body_unicode = request.body.decode("utf-8") or "{}"
            payload = json.loads(body_unicode)
        except json.JSONDecodeError:
            return JsonResponse({"code": 400, "msg": "请求体不是合法 JSON", "data": None}, status=400)

        phone = (payload.get("phone") or "").strip()

        # 手机号验证
        if not phone:
            return JsonResponse({"code": 400, "msg": "手机号不能为空", "data": None}, status=400)

        import re
        phone_pattern = r'^1[3-9]\d{9}$'
        if not re.match(phone_pattern, phone):
            return JsonResponse({"code": 400, "msg": "手机号格式不正确", "data": None}, status=400)

        from utils.redis_client import redis_client
        
        # 检查验证码是否存在
        exists = redis_client.check_sms_code_exists(phone)
        ttl = redis_client.get_sms_code_ttl(phone)
        
        if exists and ttl > 0:
            return JsonResponse({
                "code": 0,
                "msg": "验证码有效",
                "data": {
                    "phone": phone,
                    "exists": True,
                    "remaining_time": ttl,
                    "can_resend": ttl <= 240  # 剩余时间小于等于4分钟时可以重新发送
                }
            }, status=200)
        else:
            return JsonResponse({
                "code": 0,
                "msg": "验证码不存在或已过期",
                "data": {
                    "phone": phone,
                    "exists": False,
                    "remaining_time": 0,
                    "can_resend": True
                }
            }, status=200)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return JsonResponse({"code": 500, "msg": f"查询验证码状态失败: {str(e)}", "data": None}, status=500)


@csrf_exempt
@require_http_methods(["GET", "OPTIONS"])
def get_user_info(request):
    """获取用户信息接口"""
    if request.method == "OPTIONS":
        return JsonResponse({}, status=200)
    
    try:
        # 从请求头获取token
        auth_header = request.headers.get('Authorization', '')
        if not auth_header or not auth_header.startswith('Bearer '):
            token = request.headers.get('X-Token') or request.GET.get('token')
        else:
            token = auth_header.replace('Bearer ', '')
            
        if not token:
            return JsonResponse({"code": 401, "msg": "未提供认证token", "data": None}, status=401)
        
        # 验证token并获取用户信息
        try:
            payload = jwtTool.decode_token(token)
            user_id = payload.get('user_id')
            
            if not user_id:
                return JsonResponse({"code": 401, "msg": "无效的token", "data": None}, status=401)
                
            # 获取用户对象
            from django.contrib.auth import get_user_model
            User = get_user_model()
            
            try:
                user = User.objects.get(id=user_id, is_active=True)
            except User.DoesNotExist:
                return JsonResponse({"code": 401, "msg": "用户不存在或已被禁用", "data": None}, status=401)
            
            # 构建用户信息
            user_data = {
                "id": user.id,
                "username": user.username,
                "email": user.email or "",
                "phone": getattr(user, 'phone', '') or "",
                "is_active": user.is_active,
                "date_joined": user.date_joined.isoformat() if user.date_joined else None,
                "last_login": user.last_login.isoformat() if user.last_login else None,
            }
            
            # 获取用户详细信息
            try:
                profile = user.profile
                user_data.update({
                    "nickname": profile.nickname or "",
                    "avatar": profile.avatar or "",
                    "gender": profile.gender or "",
                    "bio": profile.bio or ""
                })
            except:
                # 用户可能没有profile记录，使用默认值
                user_data.update({
                    "nickname": "",
                    "avatar": "",
                    "gender": "",
                    "bio": ""
                })
            
            return JsonResponse({
                "code": 0,
                "msg": "获取用户信息成功",
                "data": user_data
            }, status=200)
            
        except Exception as e:
            return JsonResponse({"code": 401, "msg": f"token验证失败: {str(e)}", "data": None}, status=401)
            
    except Exception as e:
        import traceback
        traceback.print_exc()
        return JsonResponse({"code": 500, "msg": f"获取用户信息失败: {str(e)}", "data": None}, status=500)


